﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

namespace Devonline.AspNetCore;

/// <summary>
/// 基于 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext">数据库上下文</typeparam>
/// <typeparam name="TEntitySet">业务数据类型</typeparam>
/// <typeparam name="TKey">主键类型</typeparam>
[Authorize]
[ApiController]
public abstract class DataServiceController<TDbContext, TEntitySet, TKey>(
    ILogger<DataServiceController<TDbContext, TEntitySet, TKey>> logger,
    IDataService<TDbContext, TEntitySet, TKey> dataService) :
    ControllerBase
    where TDbContext : DbContext
    where TEntitySet : class, IEntitySet<TKey>
    where TKey : IConvertible
{
    protected readonly ILogger<DataServiceController<TDbContext, TEntitySet, TKey>> _logger = logger;
    protected readonly IDataService<TDbContext, TEntitySet, TKey> _dataService = dataService;

    /// <summary>
    /// 查询业务对象分页列表, 查询表达式会默认取出分页及过滤等参数
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public virtual async Task<IActionResult> GetAsync() => Ok(await _dataService.GetPagedResultAsync());
    /// <summary>
    /// 新增单个数据对象的 post 请求
    /// </summary>
    /// <param name="entitySet"></param>
    /// <returns></returns>
    [HttpPost]
    public virtual async Task<IActionResult> CreateAsync(TEntitySet entitySet) => Ok(await _dataService.AddAsync(entitySet));
    /// <summary>
    /// 修改单个数据对象的 put 请求
    /// </summary>
    /// <param name="entitySet"></param>
    /// <returns></returns>
    [HttpPut]
    public virtual async Task<IActionResult> UpdateAsync(TEntitySet entitySet) => Ok(await _dataService.UpdateAsync(entitySet));
    /// <summary>
    /// 使用 id 删除单个数据对象的 delete 请求
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpDelete("{id}")]
    public virtual async Task<IActionResult> DeleteAsync(TKey id)
    {
        await _dataService.DeleteAsync(id);
        return Ok();
    }
}

/// <summary>
/// 基于字符串作为主键的 DataService 的数据增删改查的基础控制器
/// </summary>
/// <typeparam name="TDbContext">数据库上下文</typeparam>
/// <typeparam name="TEntitySet">业务数据类型</typeparam>
[Authorize]
[ApiController]
public abstract class DataServiceController<TDbContext, TEntitySet>(
    ILogger<DataServiceController<TDbContext, TEntitySet>> logger,
    IDataService<TDbContext, TEntitySet> dataService) :
    DataServiceController<TDbContext, TEntitySet, string>(logger, dataService)
    where TDbContext : DbContext
    where TEntitySet : class, IEntitySet
{ }